/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData,
  pickedLineData,
  pickedVertexData,
  pickedModelData,
} from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { wsApi } from '@app-cad/server';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';

type pickedALLType = pickedFaceData | pickedLineData | pickedVertexData;

type FormDataType = {
  obj: pickedALLType[];
  fromFrame: pickedModelData;
  toFrame: pickedModelData;
  keepSrc: boolean;
};

function SetPositionDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  const { picker } = useTools();

  const initData = {
    obj: undefined,
    fromFrame: null,
    toFrame: null,
    keepSrc: true,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const obj = props?.params?.base;
      const fromFrame = props?.params?.fromFrame;
      const toFrame = props?.params?.toFrame;

      const keepSrc = props?.params?.keepSrc;
      await initEditDependency([obj, fromFrame, toFrame]);
      const defaultObj = obj
        ? (picker.generatePickObjByPickID(obj) as pickedALLType)
        : undefined;
      const defaultStart = fromFrame
        ? (picker.generatePickObjByPickID(fromFrame) as pickedModelData)
        : undefined;
      const defaultEnd = toFrame
        ? (picker.generatePickObjByPickID(toFrame) as pickedModelData)
        : undefined;
      setFormData({
        obj: [defaultObj],
        fromFrame: defaultStart,
        toFrame: defaultEnd,
        keepSrc: keepSrc,
      });
      // setObj(defaultObj);
    } else {
      setFormData(initData);
    }
  }, []);

  const checkAndFinishDraw = async () => {
    const { obj, fromFrame, toFrame } = formData;
    if (isEmpty(fromFrame) || isEmpty(toFrame)) return;

    if (isEmpty(obj)) {
      return;
    }

    excute(false);
    onClose();
  };

  const excute = async (preview: boolean) => {
    const { obj, fromFrame, toFrame, keepSrc } = formData;

    const params = {
      fromFrame: getIdOfPickedObj(fromFrame),
      toFrame: getIdOfPickedObj(toFrame),
      keepSrc: keepSrc,
    };

    if (props) {
      const res = await wsApi.setParams(props.shape, params, preview);
      if (preview) {
        previewInCommand(res);
      }
    } else {
      await confirmCommand(
        {
          a: params,
          o: obj.map((i) => getIdOfPickedObj(i)),
        },
        preview,
      );
    }
  };

  const preview = async () => {
    const { obj, fromFrame, toFrame } = formData;
    clear();
    if (isEmpty(obj) || isEmpty(fromFrame) || isEmpty(toFrame)) {
      return;
    }

    excute(true);
  };

  const isFormDataValid = () => {
    const { obj, fromFrame, toFrame, keepSrc } = formData;
    return (
      obj !== null && fromFrame !== null && toFrame !== null && keepSrc !== null
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      obj: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickALL,
        uniqueItems: true,
      },
      fromFrame: {
        type: 'string',
        format: PickInputRJSFFormat.PickFrame,
      },
      toFrame: {
        type: 'string',
        format: PickInputRJSFFormat.PickFrame,
      },
      keepSrc: {
        type: 'boolean',
        title: '显示初始元素',
        default: true,
      },
    },
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    previewInCommand,
  } = useCommand('cmd-set-position', {
    commandName: 'SetPositionTransform',
    editDxid: props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData({
          obj: v?.obj,
          fromFrame: v.fromFrame,
          toFrame: v.toFrame,
          keepSrc: v.keepSrc,
        });
      }}
      extraUiSchema={{
        obj: {
          'ui:placeholder': '请输入元素',
          'ui:autofocus': true,
        },
        fromFrame: {
          'ui:placeholder': '请输入起始坐标系',
        },
        toFrame: {
          'ui:placeholder': '请输入目标坐标系',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdSetPosition: CurvedBaseCommand = {
  id: 'CmdSetPosition',
  label: 'command.set-position',
  icon: 'commands/curved/set-position',
  create: (label: string, onClose: () => void, props: any) => (
    <SetPositionDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
